<template>
  <div class="relative flex flex-grow !flex-row flex-col items-center
            rounded-[10px] border-[1px] border-gray-200 bg-blue-50 hover:scale-105
            hover:shadow-lg bg-clip-border shadow-md shadow-[#F3F3F3] dark:border-[#ffffff33] dark:!bg-navy-800
            dark:text-white dark:shadow-none">
    <el-popover placement="bottom" trigger="click" transition="el-zoom-in-top" :persistent="false" :disabled="state.type <= 0">
      <template #reference>
        <div class="flex w-full flex-col justify-center h-[150px] " >
          <table class="h-[150px]">
            <thead>
            <tr style="border-bottom: 1px solid black">
              <th class="text-left"><span class="text-xl font-bold dark:text-white ml-4" :style="`font-size: large;color:${state.color};`">{{ seat.seatName }}</span></th>
              <th class="text-right"><span class="text-xl font-bold dark:text-white mr-4" :style="`font-size: large;color:${state.color};`">{{ seat.name }}</span></th>
            </tr>
            </thead>
            <tbody>
            <tr>
              <th rowspan="2" style="text-align:-webkit-center">
                <div class="w-[80px] h-[80px]" :style="`background-size: contain;background-image: url('/svg/${state.image}.svg')`"
                     :id="`img_${state.seatId}`"/>
              </th>
              <th>
                <p class="text-xl font-bold dark:text-white"
                   :style="`font-size:x-large;color:${state.color};`"
                   :id="`text_content_${state.seatId}`" >{{ state.textContent }}</p>
              </th>
            </tr>
            <tr>
              <th >
                  <span class="text-xl font-bold dark:text-white"
                        :style="`font-size: xxx-large;color:${state.color}`"
                        :id="`deadline_content_${state.seatId}`">
                    {{ state.type <= 0 ? (' - - ') : (state.deadline + '分钟') }}</span>
              </th>
            </tr>
            </tbody>
          </table>
        </div>
      </template>
      <template #default >
        <div style="display: grid;">
          <el-button type="success" @click="onOpenChangeSeatDialogRef" style="margin-left: 12px;margin-bottom: 5px;">切换座位</el-button>
          <el-button type="warning" @click="openEditDialog" style="margin-bottom: 5px;">下次预约</el-button>
          <el-button type="danger" @click="clickButton('end')">结束输液</el-button>
        </div>
      </template>
    </el-popover>
  </div>
</template>

<script setup lang="ts" name="infusionCore">
import mittBus from '/@/utils/mitt';
import { ElNotification } from 'element-plus';
import { watch } from 'vue';
import { changeSeatState } from '/@/api/infusion/config';

// 定义变量内容
const route = useRoute();
const emit = defineEmits(['openSeatDialog','openEditDialog']);

// 定义父组件传过来的值
const props = defineProps({
  seat: {
    type : Object,
    default: () => {
      return {
        coreId: 0,
        seatId: 0,
        seatName: '',
        name: '',
        infusionDate: '',
        syyjsc: 0,
        yjkssj: '',
        yjjssj: '',
        sjkssj: '',
        sjjssj: '',
        seatState: 0,
      };
    },
  },
});

const state = reactive({
  seatId: 0,          // 定时管理器
  alerted: false,     // 是否已经弹窗提醒过
  deadline: 0,        // 剩余时间
  textContent: '空闲', // 提示信息
  color: '#4a4a4a',      // 默认颜色
  image: 'infusion_default' ,          // 图片
  type: -1,      // -1：无人，0：有人预约未打针，1：滴液中，2：滴液结束
})

const initCountdown = () => {
  // 用实际时间计算
  state['seatId'] = setTimeout(() => {
    if (state['type'] === -1) {
      clearTimeout(state['seatId']);
      // clearInterval(state['seatId']);
      state['deadline'] = 0;
      state['alerted'] = false;
      state['color'] = '#4a4a4a';
      state['textContent'] = '空闲';
      state['image'] = 'infusion_default';
    } else if (state['type'] === 0) {
      clearTimeout(state['seatId']);
      // clearInterval(state['seatId']);
      state['deadline'] = 0;
      state['alerted'] = false;
      state['color'] = '#2ab5dc'
      state['textContent'] = '待开始';
      state['image'] = 'infusion_blue'
    } else if (state['type'] === 1) {
      state['color'] = '#00d959'
      state['image'] = 'infusion_green'
      state['textContent'] = '输液中'
      const remainingTime = state['deadline'] - 1;
      if (remainingTime > 5) {
        state['deadline']--;
        nextTick (()=> {
          initCountdown();
        });
      } else if (remainingTime > 0 && remainingTime <= 5) {
        state['color'] = '#ffb145'
        state['image'] = 'infusion_yellow'
        state['textContent'] = '即将结束'
        if (!state['alerted']) {
          state['alerted'] = true; // 标记已经提示过
          hilarity('warning', props.seat.seatName);
        }
        state['deadline']--;
        nextTick (()=> {
          initCountdown();
        });
      } else {
        state['color'] = '#e9507a'
        state['image'] = 'infusion_red'
        state['textContent'] = '输液结束'
        if (state['deadline'] > 0) {
          state['deadline']--;
        }
        clearTimeout(state['seatId']);
        // clearInterval(state['seatId']);
        hilarity('error', props.seat.seatName);
      }
    }
  }, 1000 * 60); // 每分钟更新一次倒计时
}

const hilarity = (type:string,seatName:string) => {
  if (type === 'warning') {
    ElNotification.warning({
      title: '提醒！',
      dangerouslyUseHTMLString: true,
      message: h('i', { style: 'color: teal'}, '【'+seatName+'】剩余时间不足5分钟，请注意查看！'),
    });
  } else if (type === 'error') {
    ElNotification.error({
      title: '警告！',
      dangerouslyUseHTMLString: true,
      message: h('i', { style: 'color: teal'}, '【'+seatName+'】时间已到！'),
    });
  }
};

const onOpenChangeSeatDialogRef = () => {
  let data = {
    type: 'change',
    coreId: props.seat.coreId,
    seatId: props.seat.seatId,
  }
  emit?.('openSeatDialog',data);
};

const openEditDialog = () => {
  let coreId = props.seat.coreId;
  emit?.('openEditDialog','next',coreId);
}

/**
 * 1、预计开始时间是空 ======> 没人预约
 * 2、预计时间不是空，且实际开始时间、无结束时间不为空 ======> 当日预约打针
 * 3、预计时间不是空，实际结束时间为空，且实际开始时间有 ======> 输液中
 * 4、实际结束时间有 ======> 已经结束
 */
const changeState = () => {
  let yjkssj = props.seat.yjkssj;
  // 状态为无人预约
  if (yjkssj === '' ) {
    state['type'] = -1;
    state['alerted'] = false;
    state['color'] = '#4a4a4a';
    state['image'] = 'infusion_default';
    state['textContent'] = '空闲';
    return;
  }
  let sjkssj = props.seat.sjkssj;
  let sjjssj = props.seat.sjjssj;
  let date = new Date();
  let year = date.getFullYear();
  let month = date.getMonth() + 1;
  let day = date.getDate() < 10 ? '0' + date.getDate() : date.getDate();
  let today = year + '-' + (month < 10 ? '0' + month : month) + '-' + day;
  // 不是当天就返回0
  if (today !== props.seat.infusionDate) {
    state['type'] = 1;
    state['deadline'] = 0;
    return ;
  }
  // 状态为有人预约，未开始
  if (yjkssj !== '' && sjkssj === '' && sjjssj === '') {
    state['type'] = 0;
    return ;
  }
  // 当前时间
  let dqHours = new Date().getHours();
  let dqMin = new Date().getMinutes();
  // 状态为正在输液中
  if (yjkssj !== '' && sjkssj !== '' && sjjssj === '' ) {
    state['type'] = 1;
    let yjSeconds = props.seat.syyjsc;
    // 实际开始时间 + 预计计算的秒数
    let sjksDate = new Date(props.seat.infusionDate + ' ' + props.seat.sjkssj + ':00');
    sjksDate.setSeconds(yjSeconds / 1000 );
    let yjjssjHours = sjksDate.getHours();
    let yjjssjMin = sjksDate.getMinutes();
    // 计算为分钟
    let seconds = ((yjjssjHours - dqHours) * 60 + (yjjssjMin - dqMin))
    state['deadline'] = seconds <= 0 ? 0 : seconds;
    state['color'] = '#00d959'
    state['image'] = 'infusion_green'
    state['textContent'] = '输液中'
    if (state['deadline'] > 0 && state['deadline'] <= 5) {
      state['color'] = '#ffb145'
      state['image'] = 'infusion_yellow'
      state['textContent'] = '即将结束'
    } else if (state['deadline'] === 0) {
      state['color'] = '#e9507a'
      state['image'] = 'infusion_red'
      state['textContent'] = '输液结束'
    }
  }
}

const clickButton = (type:string) => {
  const data = {
    coreId : props.seat.coreId,
    type: type,
  }
  changeSeatState(data).then(() => {
    mittBus.emit(
        "onCurrentContextmenuClick",
        Object.assign({}, { contextMenuClickId: 0, ...route })
    );
  })
}

const startCountdown = () => {
  clearTimeout(state['seatId']);
  // clearInterval(state['seatId']);
  changeState();
  initCountdown();
}

onMounted(() => {
  startCountdown();
});

window.onload = function(){
  // 监听发送消息事件
  window.addEventListener('visibilitychange',function(){
    if (document.visibilityState === 'hidden') {
      console.log('页面离开')
    } else {
      startCountdown();
    }
  });
}

// 监听是否禁用改变
watch(
    () => props.seat,
    () => {
      startCountdown();
    },
    {
      deep: true,
    }
);
</script>
